package com.health.system.action.system;

import static com.health.system.javacommon.util.Struts2JsonHelper.outJson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

import com.health.system.javacommon.base.BaseStruts2Action;
import com.health.system.javacommon.jquery.JqueryPageHelper;
import com.health.system.javacommon.jquery.ListRange;
import com.health.system.springSecurity.LogonUser;
import com.health.system.javacommon.util.StringTool;
import com.health.system.model.system.Role;
import com.health.system.service.system.RoleManager;
import com.health.system.service.system.UserManager;

/**
 * <p>Title: 角色信息 Action</p> 
 * Description: 页面通过Ajax调用Action层,返回JSONO数据
 * Copyright: Copyright (c) 2011-03 
 * Company: 
 * 
 * @author 
 * @version 1.0 
*/

public class RoleAction extends BaseStruts2Action {
	
	private RoleManager roleManager;
	private UserManager userManager;
	
	
	/** 通过spring自动注入 */
	public void setRoleManager(RoleManager manager) {
		this.roleManager = manager;
	}	
	public void setUserManager(UserManager manager) {
		this.userManager = manager;
	}
	
	/**
	 * jqGrid使用列表
	 * @throws IOException
	 * 	@PreAuthorize("hasRole('P_PERMISSION_INDEX')") 
	 */
 
	public void list() throws IOException{
		 
		PageRequest<Map> pr = JqueryPageHelper.createPageRequestForJquery(getRequest());
		//从登录用户类中取当前用户信息
		Map mapParam = pr.getFilters();
		com.health.system.springSecurity.UserInfo userInfo = LogonUser.logonUser();
		String maxRoleId = "";
		if(null!=userInfo){
			maxRoleId = userManager.getUserMaxRoleId(userInfo.getUserId());
		    mapParam.put("id", maxRoleId);
		}
		pr.setFilters(mapParam);
		Page page = roleManager.findByPageRequest(pr);
		

		List<Role> Rolelist = (List) page.getResult();
		ListRange<Role> resultList = new ListRange<Role>();
		resultList.setDataRows(Rolelist);
        resultList.setRecords(page.getTotalCount());
        resultList.setRows(page.getPageSize());
		if(page.getTotalCount()%page.getPageSize()>0){
			resultList.setTotal(page.getTotalCount() / page.getPageSize()+1);
		}else{
			resultList.setTotal(page.getTotalCount() / page.getPageSize());
		}
		resultList.setPage(pr.getPageNumber());
		outJson(resultList);
	}

	/**
	 * Role添加
	 * @throws IOException
	 */
	public void save() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			String roleJson = request.getParameter("roleJson");
			if (null != roleJson&&!"".equals(roleJson)) {
				JSONObject jsonobject =JSONObject.fromObject( roleJson );
				Role roleobj = (Role)JSONObject.toBean(jsonobject, Role.class); 
				roleManager.save(roleobj);
				result.put("success", true);
				result.put("msg", "添加成功!");
			}else{
				result.put("success", false);
				result.put("msg", "添加失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "添加失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	/**
	 * Role修改
	 * @throws IOException
	 */
	public void update() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
			try{
				HttpServletRequest request = getRequest();
				String roleJson = request.getParameter("roleJson");
				if (null != roleJson&&!"".equals(roleJson)) {
					JSONObject jsonobject =JSONObject.fromObject( roleJson );
					Role roleobj = (Role)JSONObject.toBean(jsonobject, Role.class); 
					roleobj.setId(jsonobject.get("id").toString());
					roleManager.update(roleobj);
					result.put("success", true);
					result.put("msg", "修改成功!");
				}else{
					result.put("success", false);
					result.put("msg", "修改失败 数据错误!");
				}
			}catch (Exception e){
				result.put("success", false);
				result.put("msg", "修改失败!");
				e.printStackTrace();
			}
		outJson(result);
	}
	
	/**
	 * Role删除
	 * @throws IOException
	 */
	public void delete() throws IOException{
		
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			String ids = request.getParameter("ids");
			if (null != ids&&!"".equals(ids)){
				Role role =new Role();
				role.setIdList(StringTool.stringToArray(ids));
				roleManager.removeByIdArry(role);
				result.put("success", true);
				result.put("msg", "删除成功");
			}else{
				result.put("success", false);
				result.put("msg", "删除失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "删除失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	/**
	 * 校验角色名称
	 * @throws IOException
	 */
	public void checkRoleName() throws IOException{
		try{
			HttpServletRequest request = getRequest();
			String roleName = request.getParameter("roleName");
            if(roleName!=null&&!"".equals(roleName)){
            	Map<String, Object> parameter = new HashMap<String, Object>();
    			parameter.put("name", roleName);
    			List list = roleManager.getListByMap(parameter);
    			if(list!=null && list.size()>0){
					getResponse().getWriter().print(false);
	            }else{
	            	getResponse().getWriter().print(true);
	            }
            }
		}catch (Exception e){
			getResponse().getWriter().print(false);
			e.printStackTrace();
		}
	}
	
	/**
	 * 角色下拉框所用
	 * @throws IOException
	 * @author bzq update 加增向下查询
	 */
	public void getRoleComboBox() throws IOException{
		Map<String, Object> results = new HashMap<String, Object>();
		try{
			List list =null;
			String str ="",result="",id="",parentId="",name="";
			Role role =new Role();
			//从登录用户类中取当前用户信息
			 
			com.health.system.springSecurity.UserInfo userInfo = LogonUser.logonUser();
			String maxRoleId = "";
			if(null!=userInfo){
				maxRoleId = userManager.getUserMaxRoleId(userInfo.getUserId());
				if(null!=maxRoleId){
				  role.setId(maxRoleId);
				}
			}
			list = roleManager.getRoleList(role);
			for (int i = 0; list != null && i < list.size(); i++) {
				
				role = (Role)list.get(i);
				id=role.getId();
				parentId=role.getHigherId();
				name=role.getDescription();	
				if(result==""){
					result ="{name:'"+name+"',pId:'"+parentId+"',id:'"+id+"'}";
            	}else{
					result +=",{name:'"+name+"',pId:'"+parentId+"',id:'"+id+"'}";
            	
			}
				
				//str += "<option value=\"" + role.getId() + "\">" + role.getDescription() + "</option>";
			}
			results.put("success", true);
			results.put("msg", "["+result+"]");
		}catch (Exception e){
			results.put("success", false);
			results.put("msg", "");
			e.printStackTrace();
		}
		outJson(results);
	}
	
	
	public void getRoleComboBox1() throws IOException{

		Map<String, Object> result = new HashMap<String, Object>();
		try{
			List list =null;
			String str ="";
			Role role =new Role();			
			 
			com.health.system.springSecurity.UserInfo userInfo = LogonUser.logonUser();
			String maxRoleId = "";
			if(null!=userInfo){
				maxRoleId = userManager.getUserMaxRoleId(userInfo.getUserId());
				if(null!=maxRoleId){
				  role.setId(maxRoleId);
				}
			}
			list = roleManager.getRoleList(role);
			for (int i = 0; list != null && i < list.size(); i++) {
				role = (Role)list.get(i);
				str += "<option value=\"" + role.getId() + "\">" + role.getDescription() + "</option>";
			}
			result.put("success", true);
			result.put("msg", str);
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "");
			e.printStackTrace();
		}
		outJson(result);
	
	}
	
	/**
	 * 角色复选框用
	 * @throws IOException
	 * @author bzq update 加增向下查询
	 */
	public void getCheckbox() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			List list =null;
			String str ="";
			Role role =new Role();
			//从登录用户类中取当前用户信息
			 
			com.health.system.springSecurity.UserInfo userInfo = LogonUser.logonUser();
			String maxRoleId = "";
			if(null!=userInfo){
				maxRoleId = userManager.getUserMaxRoleId(userInfo.getUserId());
				if(null!=maxRoleId){
				  role.setId(maxRoleId);
				}
			}
			list = roleManager.getRoleList(role);
			for (int i = 0; list != null && i < list.size(); i++) {
				role = (Role)list.get(i);
				//<input type="checkbox" name="qx" id="qx"/>
				str += "<input id=\"roleCheckbox\" name=\"roleCheckbox\" type=\"checkbox\" value=\"" + role.getId() + "\">" + role.getDescription() + "";
			}
			result.put("success", true);
			result.put("msg", str);
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "");
			e.printStackTrace();
		}
		outJson(result);
	}	
	
	
	/**
	 * 类别下拉树(bzq)
	 * @throws IOException
	 */
	public void getTree() throws IOException {
		Map<String, Object> results = new HashMap<String, Object>();
		String result="",id="",parentId="",name="",customerType = "";
        Map subMp = new HashMap();
        List sublist = new ArrayList();
        Role objInfo = new Role();
		HttpServletRequest request = getRequest();
		try{
			customerType = request.getParameter("customerJson");
		
			Map map = new HashMap();
			map.put("sortType", customerType);
			List list =roleManager.getTree(map);
			
			int listsize= list.size();
			
			for (int i = 0; list != null && i < listsize; i++) {
				objInfo = (Role)list.get(i);
				
				id=objInfo.getId();
				parentId=objInfo.getHigherId();
				name=objInfo.getDescription();
				if(i == 0){
					if(result==""){
						result ="{name:'"+name+"',pId:'"+parentId+"',id:'"+id+"'}";
	            	}else{
						result +=",{name:'"+name+"',pId:'"+parentId+"',id:'"+id+"'}";
	            	}
					subMp.put(id, name);
				}else{
	            	sublist.add(objInfo);
				}
			}
			if(sublist.size()>0){
	        	result=getSubTree(sublist,subMp,result);
	        }
			results.put("success", true);
			results.put("msg", "["+result+"]");
		}catch (Exception e){
			results.put("success", false);
			results.put("msg", "");
			e.printStackTrace();
		}
		outJson(results);
	}
	
	
	private String getSubTree(List sublist,Map subMp,String result) {
		String id="",parentId="",name="";
		Role objInfo = new Role();
		Map Mp = new HashMap();
        List slist = new ArrayList();
        
        for (int i = 0; i < sublist.size(); i++) { //遍历所有子节点
        	objInfo = (Role)sublist.get(i);
			id=objInfo.getId();
			parentId=objInfo.getHigherId();
			name=objInfo.getDescription();
			
			if(subMp.containsKey(parentId)){
	            String tmpstr="",tmpstr1="",tmpstr2="",tmpstr3="";
	            tmpstr  ="{name:'"+name+"',pId:'"+parentId+"',id:'"+id+"'}";
	            Mp.put(id, name);
	            if(result.indexOf("id:'"+parentId+"',open:false")!=-1){
	    			tmpstr1 =result.substring(0,result.indexOf("id:'"+parentId+"',open:false"));
	    			String str =result.substring(result.indexOf("id:'"+parentId+"',open:false"),result.length());
	    			tmpstr1 +=str.substring(0, str.indexOf("}")+1);
	    			tmpstr2 =","+tmpstr;
	    			tmpstr3 =str.substring(str.indexOf("}")+1,str.length());
	    		}else{
	    			tmpstr1 =result.substring(0,result.indexOf("id:'"+parentId+"'")+("id:'"+parentId+"'").length());
	        		tmpstr2 =",open:false},"+tmpstr;
	        		tmpstr3 =result.substring(result.indexOf("id:'"+parentId+"'")+("id:'"+parentId+"'").length()+1,result.length());
	    		}
	    		result =tmpstr1+tmpstr2+tmpstr3;
	        }else{
	        	slist.add(objInfo);
        	}
        }
        if(slist.size()>0){
        	result=getSubTree(slist,Mp,result);
        }
         
		return result;
	}


}
